#ifndef __HTTPROUTER_H__
#define __HTTPROUTER_H__

#include "HttpRequest.h"
#include "HttpResponse.h"
#include <functional>
#include <vector>
#include <regex>

class HttpRouter {
public:
    using HttpHandler = std::function<void(const HttpRequest&, HttpResponse&)>;
    
    struct Route {
        HttpMethod method;
        std::string pattern;
        std::regex regex;
        HttpHandler handler;
        
        Route(HttpMethod m, const std::string& p, HttpHandler h)
        : method(m), pattern(p), handler(h) {
            // 将URL模式转换为正则表达式
            std::string regexPattern = pattern;
            // 简单的参数匹配 :param -> ([^/]+)
            std::regex paramRegex(":(\\w+)");
            regexPattern = std::regex_replace(regexPattern, paramRegex, "([^/]+)");
            // 转义特殊字符
            std::regex escapeRegex("\\*");
            regexPattern = std::regex_replace(regexPattern, escapeRegex, ".*");
            regex = std::regex("^" + regexPattern + "$");
        }
    };
    
public:
    HttpRouter();
    ~HttpRouter();
    
    // 注册路由
    void get(const std::string& path, HttpHandler handler);
    void post(const std::string& path, HttpHandler handler);
    void put(const std::string& path, HttpHandler handler);
    void del(const std::string& path, HttpHandler handler);  // delete是关键字
    void options(const std::string& path, HttpHandler handler);
    
    // 通用路由注册
    void route(HttpMethod method, const std::string& path, HttpHandler handler);
    
    // 静态文件服务
    void serveStatic(const std::string& urlPrefix, const std::string& localPath);
    
    // 处理请求
    bool handleRequest(const HttpRequest& request, HttpResponse& response);
    
    // 中间件支持
    using Middleware = std::function<bool(const HttpRequest&, HttpResponse&)>;
    void use(Middleware middleware);

private:
    std::vector<Route> _routes;
    std::vector<Middleware> _middlewares;
    std::string _staticUrlPrefix;
    std::string _staticLocalPath;
    
    bool matchRoute(const Route& route, const HttpRequest& request);
    void handleNotFound(HttpResponse& response);
    void handleMethodNotAllowed(HttpResponse& response);
    void handleStaticFile(const std::string& filePath, HttpResponse& response);
    std::string getContentType(const std::string& filePath);
};

#endif